//
//  NLUserAccountViewModel.swift
//  sinaWeibo7110
//
//  Created by 安静清晨 on 2017/1/8.
//  Copyright © 2017年 walk-in-minds. All rights reserved.
//

import UIKit

//========================================
//单例bug---需要确保以下:
//在登录状态下, 确保account有值
//从未登录状态到登录状态时, 确保account有值
//========================================

private let cacheAccountPath = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last! as NSString).appendingPathComponent("account.plist")

class NLUserAccountViewModel: NSObject {

    //因为在App中一次只可能登录一个账户, 所以直接设计成单例
    static let shared : NLUserAccountViewModel = NLUserAccountViewModel()
    
    //ViewModel持有的数据模型
    var account: NLUserAccount?
    
    //单例对象只会实例化一次, 一旦删除了应用再加载就不会再调用 MARK:problem
    override init() {
        super.init()
        //给userAccount赋值 确保用户在登录的情况下能够给单例对象的模型赋值
        self.account = self.loadUserAccount()
    }
    
    
    
    
    //封装数据的业务逻辑处理
    //判断用户是否登录
    //判断令牌是否 不为nil且没有过期
    //没有过期的判断标准 expires_date 大于当前日期
    
    var isLogin: Bool{
        
        if account?.access_token != nil && isExpires == false{
            
            //print("~~~~~~~~~~")
            return true
        }
        
        return false
    }
    
    var isExpires:Bool{
        
        
        
        if account?.expires_date?.compare(Date()) == .orderedDescending{
            
            return false
        }
        
        return true
    }
    
    
    
    
    //ViewModel(视图模型)
    
    //1.封装网络请求
    //2.通过code获取令牌 access_token
    func loadAccessToken(code:String, finished:@escaping (Bool)->()){
        
        //https://api.weibo.com/oauth2/access_token, POST请求
        let urlString = "https://api.weibo.com/oauth2/access_token"
        
        //参数-字典
        let dict = ["client_id":client_id,
                    "client_secret":client_secret,
                    "grant_type":grant_type,
                    "code":code,
                    "redirect_uri":redirect_uri]
        
        HMNetworkTools.shared.request(method: .POST, urlString: urlString, parameters: dict, finished: {(resp, error)->() in
            
            if error != nil{
                
                finished(false)
    
                return
                
            }else{
                
                //print(resp!)
                //3.通过令牌请求用户信息
                self.loadUserInfo(dict: resp as! [String : Any], finishedLoadUserInfo: finished)
                //这里不能直接返回true. 因为用户信息还没拿到
            }
            
        })
        
    }
    
    private func loadUserInfo(dict:[String:Any], finishedLoadUserInfo: @escaping (Bool)->()){
        
        
        //参数: access_token  uid
        let access_token = dict["access_token"]!
        let uid = dict["uid"]!//MARK:有可能会有问题, 有问题的时候这里加!
        let parameters = ["access_token" : access_token,
                          "uid" : uid]
        print(parameters)
        let urlString = "https://api.weibo.com/2/users/show.json"
        HMNetworkTools.shared.request(method: .GET, urlString: urlString, parameters: parameters) { (resp, error) in
            if error != nil {
                //错误提示
                //SVProgressHUD.showError(withStatus: "没有网络")
                return
            }
            
            //print(resp!)
            
            
            
            var userInfoDict = resp as! [String:Any]
            //3.1将令牌字典合并到用户信息字典
            for (key,value) in dict{
                
                userInfoDict[key] = value
                
            }
            //3.2字典转模型
            let userAccount = NLUserAccount(dict:userInfoDict)
            
            print("userAccount======",userAccount)
            
            //MARK:problem 直接给单例对象赋值
            self.account = userAccount
            //print("account=====",self.account?.access_token, self.account?.screen_name)
            //把userAccount传给欢迎界面
//            let welcomeVC = NLWelcomeViewController()
//            welcomeVC.account! = self.account
//            
            //4. 将模型数组 归档
            self.saverUserAccount(account: userAccount)
            finishedLoadUserInfo(true)
        }
    }
    
    
    //4. 将用户信息归档
    private func saverUserAccount(account:NLUserAccount){
        // 在String中没有拼接文件路径的方法 需要转换为NSString
//        let path = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last! as NSString).appendingPathComponent("account.plist")
        NSKeyedArchiver.archiveRootObject(account, toFile: cacheAccountPath)
//        print(path)
    }
    
    //通过解档的方式获取用户信息的模型
    func loadUserAccount() -> NLUserAccount? {
        
        print(cacheAccountPath)
        if let cacheAccount = NSKeyedUnarchiver.unarchiveObject(withFile: cacheAccountPath) as? NLUserAccount{
            //如果解档不为nil  并且能够转换为HMUserAccount类型的对象 就任务用户用户的信息就能够获取
            return cacheAccount
        }
        //默认无法获取用户模型对象
        return nil
    }

  
    
    //3. 封装数据缓存和数据获取的操作
    
    
}
